package com.xf.auth.service.impl;


import com.xf.common.core.authe.feign.UserConsumer;
import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.entity.FebsAuthUser;
import com.xf.common.core.entity.system.SystemUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author xufeng
 */
@Slf4j
@Service("sysUserDetailService")
@RequiredArgsConstructor
public class FebsUserDetailServiceImpl implements UserDetailsService {

    private final UserConsumer userManager;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        DmpResult<SystemUser> dmpResult = userManager.findByName(username);
        if (dmpResult == null || dmpResult.getData() == null) {
            String message = Optional.ofNullable(dmpResult).map(DmpResult::getMsg)
                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            throw new UsernameNotFoundException(message);
        } else {
            SystemUser systemUser = dmpResult.getData();
            String password = systemUser.getPassword();
            boolean notLocked = false;
            if (SystemUser.STATE_VALID.equals(systemUser.getState())) {
                notLocked = true;
            }
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(systemUser.getRoleList())) {
                grantedAuthorities = AuthorityUtils.createAuthorityList(
                        systemUser.getRoleList().toArray(new String[systemUser.getRoleList().size()]));
            }
            FebsAuthUser authUser = new FebsAuthUser(systemUser.getUserName(), password, true,
                    true, true, notLocked, grantedAuthorities);
            BeanUtils.copyProperties(systemUser, authUser);
            authUser.setTenantId(systemUser.getTenantId());
            authUser.setUserId(systemUser.getId());
            return authUser;
        }
    }
}
